package com.boby.homecamera.activity.client


import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.SurfaceView
import android.view.View
import android.view.WindowInsetsController
import android.widget.FrameLayout
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import androidx.core.graphics.toColorInt
import androidx.core.view.WindowInsetsControllerCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.recyclerview.widget.RecyclerView
import com.boby.homecamera.R
import com.boby.homecamera.adapter.VideoAdapter
import com.boby.homecamera.db.CameraDeviceTable.CameraDevice
import com.boby.homecamera.db.VideoTable.Video
import com.boby.homecamera.helper.SimpleVideoPlayer
import com.boby.homecamera.net.Api
import com.boby.homecamera.util.DateUtil
import com.boby.homecamera.util.DateUtil.getDayStartTimeMillis
import com.boby.homecamera.util.DateUtil.getDayStartTimeSecond
import com.boby.homecamera.view.RtspView
import com.boby.homecamera.view.TabHorizontalScrollView
import com.boby.homecamera.view.TimeRuleView
import com.boby.homecamera.view.TimeRuleView.TimePart
import com.boby.homecamera.view.TimelineView
import com.boby.homecamera.view.TimelineView.TimeRecord
import com.boby.lib_common.base.BaseActivity
import com.boby.lib_common.extens.dp
import com.boby.lib_common.extens.getParcelableExtraData
import com.boby.lib_common.extens.scrollToCenter
import com.boby.lib_common.network.Net
import com.boby.lib_common.util.BLog
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.Random
import kotlin.math.max
import androidx.core.view.isVisible
import androidx.media3.common.util.UnstableApi
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.boby.homecamera.db.VideoEventTable
import com.boby.homecamera.db.VideoTable
import com.boby.homecamera.fragment.client.VideoEventMsgFragment
import com.boby.homecamera.fragment.client.VideoHistoryFragment
import com.boby.homecamera.service.ClientMsgService
import com.boby.homecamera.view.MyRecyclerView
import com.boby.lib_common.extens.getScreenWidth
import com.boby.lib_common.extens.runOnMainThread
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator


class CameraClientActivity : BaseActivity() {
    private val TAG = "CameraClientActivity"
    private lateinit var tv_title : TextView
    private lateinit var mCameraDevice:CameraDevice
    private lateinit var mRtspView:RtspView
    private lateinit var sv_video: SurfaceView
    private lateinit var tv_back_live: TextView
    private lateinit var viewPager2: ViewPager2
    private lateinit var tabLayout: TabLayout
    private var mSimpleVideoPlayer:SimpleVideoPlayer? = null
    private var mVideoEventMsgFragment: VideoEventMsgFragment? = null
    private var mVideoHistoryFragment: VideoHistoryFragment? = null
    companion object{
        fun start(activity: Context,cameraData:CameraDevice ){
            val intent = Intent(activity, CameraClientActivity::class.java)
            intent.putExtra("data",cameraData)
            activity.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_camera_client)

        val toolbar: Toolbar = findViewById(R.id.mToolbar)
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true) // 显示返回按钮
//        initToolBar(toolbar)
        mCameraDevice = intent.getParcelableExtraData<CameraDevice>("data", CameraDevice::class.java)!!
        initView()
        initData()
        bindMsgServer()
    }
//    override fun initSystemBar() {
//
//    }
    override fun onSupportNavigateUp(): Boolean {
        finish()
        return true
    }
private var isPause = false
    override fun onPause() {
        super.onPause()
        isPause = true
//        if(mRtspView.isVisible){
//            mRtspView.stop()
//        }
    }

    override fun onResume() {
        super.onResume()
//        if(mRtspView.isVisible && isPause){
//            startRtsp()
//        }
        isPause = false
    }

    private fun initView(){
        val fl_preview = findViewById<FrameLayout>(R.id.fl_preview)
        val layoutParams = fl_preview.layoutParams

        layoutParams.height = (getScreenWidth()*9f/16f).toInt()
        fl_preview.layoutParams = layoutParams
        tv_title = findViewById(R.id.tv_title)
        mRtspView = findViewById(R.id.mRtspView)
        sv_video = findViewById(R.id.sv_video)
        tv_back_live = findViewById(R.id.tv_back_live)
        viewPager2 = findViewById(R.id.viewPager2)
        tabLayout = findViewById(R.id.tabLayout)
        tv_back_live.setOnClickListener {
            tv_back_live.visibility = View.GONE
            sv_video.visibility = View.GONE
            mSimpleVideoPlayer?.setListenerTime(false)
            mSimpleVideoPlayer?.pause()
            mRtspView.visibility = View.VISIBLE
            startRtsp()
        }
        initTabView()
    }

    private fun initData(){

        tv_title.text = mCameraDevice.deviceName

        startRtsp()
    }


    private fun initTabView(){


        mSimpleVideoPlayer = SimpleVideoPlayer(this,sv_video)
        val titles = listOf( "实时", "回看")
        mVideoHistoryFragment = VideoHistoryFragment.newInstance(mCameraDevice.ip,mCameraDevice.token,mCameraDevice.httpPort)
        mVideoEventMsgFragment = VideoEventMsgFragment.newInstance(mCameraDevice.ip,mCameraDevice.token,mCameraDevice.httpPort)
        val fragments = mutableListOf( mVideoEventMsgFragment!!,mVideoHistoryFragment!!)
        tabLayout.setTabTextColors("#333333".toColorInt(),Color.BLACK)
        viewPager2.adapter = object : FragmentStateAdapter(this) {
            override fun getItemCount() = fragments.size
            override fun createFragment(position: Int) = fragments[position]
        }

        // 关闭回收机制，预加载所有页面（性能允许时）
        viewPager2.offscreenPageLimit = fragments.size

        TabLayoutMediator(tabLayout, viewPager2) { tab, position ->
            tab.text = titles[position]
        }.attach()
    }
    private fun startRtsp(){
        mRtspView.start(Api.getRtspUrl(mCameraDevice.ip,mCameraDevice.streamPort),mCameraDevice.userName,mCameraDevice.token)
    }

    override fun onDestroy() {
        super.onDestroy()

        unBindMsgServer()
        mRtspView.stop()
        mSimpleVideoPlayer?.release()
        mSimpleVideoPlayer = null
    }
     var lastPlayMsgVideo = true
    fun playVideoMsg(videos: List<Video>,offsetTime:Long){
        if(mRtspView.isVisible){
            mRtspView.visibility = View.GONE
            mRtspView.stop()
            sv_video.visibility = View.VISIBLE
            tv_back_live.visibility = View.VISIBLE
        }
        lastPlayMsgVideo = true
        mSimpleVideoPlayer?.setVideoList(videos,mCameraDevice.ip,mCameraDevice.httpPort,mCameraDevice.token)
        mSimpleVideoPlayer?.seekTo(0,if(offsetTime>0) offsetTime else 0)
        mSimpleVideoPlayer?.setTimeListener(null)
        mSimpleVideoPlayer?.setListenerTime(false)
        mSimpleVideoPlayer?.play()
    }

    fun playVideoItem(index:Int,item:VideoTable.Video){
        if(mRtspView.isVisible){
            mRtspView.visibility = View.GONE
            mRtspView.stop()
            sv_video.visibility = View.VISIBLE
            tv_back_live.visibility = View.VISIBLE
        }
//            BLog.d(TAG,"click index: $index item: $item")
        mSimpleVideoPlayer?.seekTo(index,0L)
        mSimpleVideoPlayer?.setListenerTime(true)
        mSimpleVideoPlayer?.play()
    }
    fun seekVideo(index:Int,offsetTime: Long) {
        if(sv_video.isVisible){
            mSimpleVideoPlayer?.seekTo(index,offsetTime)
            mSimpleVideoPlayer?.setListenerTime(true)
            mSimpleVideoPlayer?.play()
        }
    }
    fun setVideoPlayerTimeListener(listener:((index:Int,contentDuration: Long,duration:Long)->Unit)?){
        mSimpleVideoPlayer?.setTimeListener(listener)
    }
    fun setVideoList(videos: List<Video>){
        lastPlayMsgVideo = false
        mSimpleVideoPlayer?.setVideoList(videos,mCameraDevice.ip,mCameraDevice.httpPort,mCameraDevice.token)
    }


    private fun bindMsgServer() {
        val intent = Intent(this, ClientMsgService::class.java)
//        startService(intent)
        bindService(intent, serviceConnection, BIND_AUTO_CREATE)
    }
    private fun unBindMsgServer() {
        if(msgBinder != null){
//            msgBinder?.sendFlashMsg(mCameraDevice.deviceId,false)
            msgBinder?.removeClient(mCameraDevice.deviceId)
            unbindService(serviceConnection)
            msgBinder = null
        }
    }
    private var msgBinder:ClientMsgService.LocalBinder? = null
    private val serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            BLog.d(TAG,"onServiceConnected")
            if(mCameraDevice.token.isNullOrEmpty()){
                return
            }
            msgBinder = service as ClientMsgService.LocalBinder
            msgBinder?.addClient( mCameraDevice.deviceId,Api.getIP(mCameraDevice.ip),mCameraDevice.websocketPort,mCameraDevice.token!!){
                mVideoEventMsgFragment?.addNewVideoEvent(it)
            }
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            msgBinder = null
        }
    }
    fun getClientMsgServiceBinder() = msgBinder
    fun setFlash(flashOn: Boolean){
        msgBinder?.sendFlashMsg(mCameraDevice.deviceId,flashOn)
    }
    fun setAudioCall(isStart: Boolean) {
        msgBinder?.setAudioCall(mCameraDevice.deviceId,isStart)
    }
    fun sendAudioMsg(byteArray: ByteArray){
        msgBinder?.sendAudioMsg(mCameraDevice.deviceId,byteArray)
    }



}